<template>
  <div class="pagestyle">
    <list_controller :style="{ width: state.listBtnType == 6 ? '78%' : '100%' }" ref="zujianname"
      :options="state.options">
      <template v-slot:opraCurdBtnlist="row">
        <span>
          <el-button class="tableFontSize" type="primary" link size="small" @click="lookBtn(row.row.row)">填写分析
          </el-button>
          <el-button class="tableFontSize" type="primary" link size="small" v-if="row.row.row.templateDto != null"
            @click="editBtn(row.row.row)">查看分析
          </el-button>
        </span>
      </template>
      <template v-slot:opraCurdBtnAll>
        <span :class="state.listBtnType == 1 ? 'listInfoBtn active' : 'listInfoBtn'" @click="listInfoBtnClick(1)">
          <svg-icon :class="state.listBtnType == 1 ? 'active' : ''" class-name="search-icon" icon-class="qiehuan" />
          历史断电
        </span>
        <span :class="state.listBtnType == 2 ? 'listInfoBtn active' : 'listInfoBtn'" @click="listInfoBtnClick(2)">
          <svg-icon :class="state.listBtnType == 2 ? 'active' : ''" class-name="search-icon"
            icon-class="shouyetaishifenxi" />
          态势分析
        </span>
        <span :class="state.listBtnType == 6 ? 'listInfoBtn active' : 'listInfoBtn'" @click="listInfoBtnClick(6)">
          <svg-icon :class="state.listBtnType == 6 ? 'active' : ''" class-name="search-icon" icon-class="qiehuan" />
          统计数据
        </span>
      </template>
      <template v-slot:selectNamelist> 实时断电信息 </template>
      <template v-slot:listSS="{ row, field }">
        <div v-if="field == 'cutAccumulationTime'">{{computTime(row)}}</div>
        <div v-if="field == 'sensorType'">
          <el-tag type="primary" v-if="row.sensorType == '开关量'">
            {{row.sensorType}}
          </el-tag>
          <el-tag style="color:#7777ee;border-color:#7777ee;" color="rgba(119, 119, 238, 0.1)"
            v-if="row.sensorType == '模拟量'">
            {{row.sensorType}}
          </el-tag>
        </div>
        <div v-if="field == 'status'">
          <span v-if="row.status !=null">
            <el-tag type="danger" v-for="item in row.status.split(',')" style="margin-right: 5px;" :key="item">{{item }}
            </el-tag>
          </span>
        </div>
        <div v-if="field == 'deviceStatus'">
          <el-tag type="danger" v-if="row.deviceStatus?.includes('网络故障')">
            {{row.deviceStatus}}
          </el-tag>
          <el-tag type="warning" v-else-if="row.deviceStatus?.includes('分站故障')">
            {{row.deviceStatus}}
          </el-tag>
          <el-tag type="primary" v-else-if="row.deviceStatus">
            {{row.deviceStatus}}
          </el-tag>
        </div>
      </template>
    </list_controller>
    <!-- 填写分析 -->
    <fillayaCom :fillayaComShow="state.fillayaComShow" @submitFormfillayaCom="submitFormfillayaCom" :status="'A'">
    </fillayaCom>
    <ayadetailCom :detailsList="state.detailsList" :detailsShow="state.detailsShow"></ayadetailCom>

    <ayasdataCom style="width: 21.5%" v-if="state.listBtnType == 6" @close="close" :dataOption="state.dataOption">
      <template v-slot:ayasContent>
        <ayasCardCom title="区域断电统计" :list="state.ayasObjData.oneList.length">
          <template v-slot:rightoperate>
            <span class="rightayasSel">
              <span @click="rightayasSelTypeClick(item)"
                :class="state.ayasObjData.rightayasSelType==item.type?'active':''"
                v-for="item in [{type:'O',label:'近24小时'},{type:'S',label:'近7天'}]">
                {{ item.label }}
              </span>
            </span>
          </template>
          <template v-slot:operatecontent>
            <div class="ayasTjBox">
              <div class="ayasTjBoxdesc" v-for="item in state.ayasObjData.oneList">
                <p>{{item.areaName}}</p>
                <p><em>{{item.count}}</em>次</p>
              </div>
            </div>
          </template>
        </ayasCardCom>
        <ayasCardCom title="异常统计" :list="3">
          <template v-slot:operatecontent>
            <div class="yichangBox">
              <div class="itemBox" @click="toLSPage('Cx_hisAlarmList')">
                <img src="@/assets/images/abnormal.png" alt="" />
                <p>报警</p>
                <p class="num" style="color: rgba(255, 153, 0, 1);">{{ state.ayasObjData.twoObj.alarmCount }}</p>
              </div>
              <div class="itemBox" @click="toLSPage('Cx_hisCutList')">
                <img src="@/assets/images/abnormal.png" alt="" />
                <p>断电</p>
                <p class="num" style="color: rgba(255, 85, 85, 1);">{{ state.ayasObjData.twoObj.cutCount }}</p>
              </div>
              <div class="itemBox" @click="toLSPage('Cx_hisFeedList')">
                <img src="@/assets/images/abnormal.png" alt="" />
                <p>馈电</p>
                <p class="num" style="color: rgba(238, 102, 187, 1);">{{ state.ayasObjData.twoObj.feedCount }}</p>
              </div>
            </div>
          </template>
        </ayasCardCom>
        <ayasCardCom title="断电次数及时长统计" :list="state.ayasObjData.threeList.length">
          <template v-slot:rightoperate>
            <span class="rightayasSel">
              <span @click="threeClick(item)" :class="state.ayasObjData.threeSelType==item.type?'active':''"
                v-for="item in [{type:'O',label:'近24小时'},{type:'S',label:'近7天'}]">
                {{ item.label }}
              </span>
            </span>
          </template>
          <template v-slot:operatecontent>
            <div id="chartBox" style="width: 100%;height: 200px;">
            </div>
          </template>
        </ayasCardCom>
        <ayasCardCom title="断电测点控制馈电异常" :list="state.ayasObjData.fourList.length">
          <template v-slot:rightoperate>
            <span class="rightayasSel">
              <span @click="fourClick(item)" :class="state.ayasObjData.fourSelType==item.type?'active':''"
                v-for="item in [{type:'O',label:'近24小时'},{type:'S',label:'近7天'}]">
                {{ item.label }}
              </span>
            </span>
          </template>
          <template v-slot:operatecontent>
            <div id="chartBoxt" style="width: 100%;height: 200px;">
            </div>
          </template>
        </ayasCardCom>
      </template>
    </ayasdataCom>
    <!-- 详情 -->
    <el-drawer v-model="state.drawerShow" direction="rtl" size="50%" close-on-click-modal :modal="true">
      <template #header="{ close, titleId, titleClass }">
        <h4 class="mask_sub_title" style="color:#3E464F;margin:0;">
          <svg-icon class-name="search-icon" icon-class="biaotitubiao" /><span>态势分析</span></h4>
      </template>
      <div>
        <realChartCutCom :targetTime="state.targetTime" :pointDataList="state.pointDataList"
          :drawerShow="state.drawerShow"></realChartCutCom>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
  import fillayaCom from "./listCom/fillayaCom.vue";
  import ayadetailCom from "./listCom/ayadetailCom.vue";
  import list_controller from "@/components/commonCom/list_controller";
  import realChartCutCom from "./listCom/realChartCutCom.vue";
  import ayasdataCom from "./listCom/ayasdataCom.vue";
  import ayasCardCom from "./listCom/ayasCardCom.vue";
  import {
    computed,
    reactive,
    nextTick
  } from "vue";
  import {
    table_headers
  } from "@/components/commonCom/table_headers";
  import axios from "@/utils/request";
  import usePagesStore from "@/store/modules/pages";
  import dayjs from "dayjs";
  import * as echarts from "echarts";
  const {
    proxy
  } = getCurrentInstance();
  const store = usePagesStore();
  const router = useRouter();
  let previewHttps =
    import.meta.env.VITE_APP_HTTP;
  const upload = ref(null);
  let state = reactive({
    ayasObjData: {
      rightayasSelType: 'S',
      oneList: [],
      twoObj: {},
      threeSelType: 'S',
      threeList: [],
      fourList: [],
      fourSelType: 'S'
    },
    detailsShow: false,
    detailsList: [],
    fillayaComShow: false, //控制填写分析抽屉显示
    listBtnType: undefined,
    options: {
      refreshShow: true,
      tableheads: computed(() => table_headers.listPointCut),
      listSS: [{
          field: "sensorType",
          filterField: {
            field: "sensorType",
            options: [{
                label: "开关量",
                value: "开关量",
                checked: false,
              },
              {
                label: "模拟量",
                value: "模拟量",
                checked: false,
              },
              {
                label: "累计量",
                value: "累计量",
                checked: false,
              },
            ]
          },
        },
        {
          field: "status",
          filterField: {
            field: "status",
            options: [{
                label: "断电",
                value: "断电",
                checked: false,
              },
              {
                label: "报警",
                value: "报警",
                checked: false,
              },
              {
                label: "标校",
                value: "标校",
                checked: false,
              },
            ]
          },
        },
        {
          field: "deviceStatus",
          filterField: {
            field: "deviceStatus",
            options: [{
                label: "正常",
                value: "正常",
                checked: false,
              },
              {
                label: "网络故障",
                value: "网络故障",
                checked: false,
              },
              {
                label: "分站故障",
                value: "分站故障",
                checked: false,
              },
              {
                label: "断线",
                value: "断线",
                checked: false,
              },
            ]
          },
        },
        {
          field: "cutAccumulationTime"
        },
      ],
      queryList: {
        querys: [],
      },
      dataUrl: "/realPointCut/listPointCuts",
    },
    tempList: [],
    // 表单
    editId: undefined,
    dataOption: {
      oneTitle: '区域断电统计',
      twoTitle: '近24小时异常统计',
      threeTitle: '断电次数及时长统计',
      fourTitle: '断电测点控制馈电异常',
      oneUrl: '/realPointCut/attainCutAreaInfo',
      twoUrl: '/realPointAlarm/attainAnomalyInfo',
      threeUrl: '/hisPointCut/listCutInfoStatistic',
      fourUrl: '/hisPointFeed/listFeedStatistic'
    },
    drawerShow: false,
    pointDataList: [],
    targetTime: '',
  });
  /**
   * 统计数据/hisPointFeed/listFeedInfoStatistic
   */
  function getoneList() {
    axios.post('/realPointCut/attainCutAreaInfo', {
      type: state.ayasObjData.rightayasSelType
    }).then(res => {
      state.oneList = res.data.cutAreaStatisticDtoList
    })
  }
  // 24小时异常
  function getattainAnomalyInfo() {
    axios.get('realPointAlarm/attainAnomalyInfo').then(res => {
      state.ayasObjData.twoObj = res.data
    })
  }
  // 统计数据
  function rightayasSelTypeClick(item) {
    state.ayasObjData.rightayasSelType = item.type
    getoneList()
  }



  function threeClick(item) {
    state.ayasObjData.threeSelType = item.type
    getlistAlarmInfoStatistic()

  }

  function toLSPage(url) {
    router.push({
      name: url
    })
  }
  let chartBox, chartBoxt

  function setC1(xdata, data, data1) {
    let option = {
      grid: {
        bottom: 30,
        right: 40
      },
      legend: {
        show: true,
        x: "center",
        textStyle: {
          color: "rgba(62, 70, 79, 1)",
        },
      },
      xAxis: [{
        type: "category",
        boundaryGap: false,
        axisLabel: {
          color: 'rgba(62, 70, 79, 1)',
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: "rgba(62, 70, 79, 1)",
          },
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          show: false,
          lineStyle: {
            color: "#195384",
          },
        },
        data: xdata,
      }],
      yAxis: [{
          type: "value",
          name: "次数",
          axisLabel: {
            textStyle: {
              color: "rgba(62, 70, 79, 1)",
            },
          },
          axisLine: {
            lineStyle: {
              color: "rgba(62, 70, 79, 1)",
            },
          },
          axisTick: {
            show: false,
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: "#11366e",
            },
          },
        },
        {
          type: "value",
          name: "时长",
          axisLabel: {
            textStyle: {
              color: "rgba(62, 70, 79, 1)",
            },
          },
          axisLine: {
            lineStyle: {
              color: "rgba(62, 70, 79, 1)",
            },
          },
          axisTick: {
            show: false,
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: "#11366e",
            },
          },
        },
      ],
      series: [{
          name: "报警次数",
          type: "line",
          symbol: "none",
          yAxisIndex: 0,
          itemStyle: {
            normal: {
              lineStyle: {
                color: "rgba(68, 170, 255, 1)",
                width: 2,
              },
            },
          },
          data: data,
        },
        {
          name: "报警时长",
          type: "line",
          yAxisIndex: 1,
          symbol: "none",
          itemStyle: {
            normal: {
              lineStyle: {
                color: "rgba(95, 212, 171, 1)",
                width: 2,
              },
            },
          },
          data: data1,
        }
      ],
    };
    chartBox.setOption(option, true)
  }

  function getlistAlarmInfoStatistic() {
    axios.post('/hisPointCut/listCutInfoStatistic', {
      type: state.ayasObjData.threeSelType
    }).then(res => {

      state.ayasObjData.threeList = res.data.cutInfoStatisticDtoList
      let xdata = res.data.cutInfoStatisticDtoList.map(item => {
        return item.sensorName + '\n' + item.pointId
      })
      let data = res.data.cutInfoStatisticDtoList.map(item => {
        return item.alarmCount
      })
      let data1 = res.data.cutInfoStatisticDtoList.map(item => {
        return item.alarmTime
      })
      nextTick(() => {
        chartBox = echarts.init(document.getElementById("chartBox"));
        setC1(xdata, data, data1)
      })
    })
  }

  function setC2(xdata, data) {
    let option = {
      grid: {
        left: 50,
        bottom: 30,
        right: 30
      },
      xAxis: {
        show: false,
      },
      yAxis: [{
          show: true,
          data: xdata,
          inverse: true,
          axisLine: {
            show: false,
          },
          splitLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            color: "rgba(62, 70, 79, 1)",
            rich: {
              lg: {
                backgroundColor: "#339911",
                color: "#fff",
                borderRadius: 15,
                // padding: 5,
                align: "center",
                width: 15,
                height: 15,
              },
            },
          },
        },
        {
          show: true,
          inverse: true,
          data: data,
          axisLabel: {
            show: true,
            inside: false,
            textStyle: {
              color: "rgba(62, 70, 79, 1)",
              fontSize: "12",
            },
            formatter: function (val) {
              return `${val}`;
            },
          },
          axisLine: {
            show: false,
          },
          splitLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
        },
      ],
      series: [{
        type: "bar",
        yAxisIndex: 0,
        data: data,
        barWidth: 30,
        itemStyle: {
          normal: {
            color: " #56A7FF",
          },
        }
      }],
    };
    chartBoxt.setOption(option, true)
  }

  function getattainRealAreaInfo2() {
    axios.post('/hisPointFeed/listFeedStatistic', {
      type: state.ayasObjData.fourSelType
    }).then(res => {
      state.ayasObjData.fourList = res.data.feedPointDtoList
      let xdata = res.data.feedPointDtoList.map(item => {
        return item.areaName
      })
      let data = res.data.feedPointDtoList.map(item => {
        return item.count
      })
      nextTick(() => {
        chartBoxt = echarts.init(document.getElementById("chartBoxt"));
        setC2(xdata, data)
      })
    })
  }

  function fourClick(item) {
    state.ayasObjData.fourSelType = item.type
    getattainRealAreaInfo2()
  }
  // 填写分析抽屉
  function lookBtn(row) {
    state.editId = row.id;
    state.fillayaComShow = dayjs().unix();
  }
  // 提交填写分析
  function submitFormfillayaCom(data) {
    let dataObj = {};
    dataObj.id = state.editId;
    dataObj.templateDto = data;
    if (data) {
      axios.post("/realPointTemplate/modifyAnalysis", dataObj).then((res) => {
        proxy.$modal.msgSuccess(res.msg);
        state.fillayaComShow = false;
        proxy.$refs.zujianname.getData({});
      });
    } else {
      state.fillayaComShow = false;
    }
  }
  // 新增按钮
  function listInfoBtnClick(type) {
    state.listBtnType = type;
    if (type == 1) {
      goPage()
    }
    if (type == 2) {
      if (proxy.$refs.zujianname.vxe.state.records.length > 0) {
        state.drawerShow = true
        state.pointDataList = proxy.$refs.zujianname.vxe.state.records
      } else {
        proxy.$modal.msgWarning('请先选择数据!')
      }
    }
    if (type == 6) {
      getoneList()
      getattainAnomalyInfo()
      getlistAlarmInfoStatistic()
      getattainRealAreaInfo2()
    }
  }
  // 编辑按钮
  function editBtn(row) {
    state.detailsShow = dayjs().unix();
    state.detailsList = row.templateDto;
  }
  // 关闭统计数据
  const close = () => {
    state.listBtnType = undefined
  }
  // 计算累计时间
  let formattedTime = ref('')
  const computTime = (row) => {
    if (row.cutAccumulationTime) {
      setInterval(() => {
        const now = new Date(); // 当前时间
        const target = new Date(row.cutStartTime); // 目标时间
        const diff = Math.abs(now - target); // 时间差（毫秒）
        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        const hours = Math.floor((diff / (1000 * 60 * 60)) % 24);
        const minutes = Math.floor((diff / (1000 * 60)) % 60);
        const seconds = Math.floor((diff / 1000) % 60);
        row.cutAccumulationTime = `${days}天${hours}时${minutes}分${seconds}秒`;
      }, 1000);
    } else {
      const now = new Date(); // 当前时间
      const target = new Date(row.cutStartTime); // 目标时间
      const diff = Math.abs(now - target); // 时间差（毫秒）
      const days = Math.floor(diff / (1000 * 60 * 60 * 24));
      const hours = Math.floor((diff / (1000 * 60 * 60)) % 24);
      const minutes = Math.floor((diff / (1000 * 60)) % 60);
      const seconds = Math.floor((diff / 1000) % 60);
      row.cutAccumulationTime = `${days}天${hours}时${minutes}分${seconds}秒`;
    }
    return row.cutAccumulationTime
  }

  // 跳转历史断电异常页面
  const goPage = () => {
    router.push({
      name: 'Cx_hisCutList'
    })
  }
</script>
<style lang="scss" scoped>
  .xiazai {
    position: absolute;
    top: 42px;
    right: 241px;
    width: 120px;
    height: 64px;
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: space-between;
    background-color: #ffff;
    box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
    border-radius: 2px;
    z-index: 99;

    .item {
      width: 100%;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }

    .item:hover {
      background-color: #ececec;
    }
  }

  .pagestyle {
    display: flex;
    justify-content: space-between;
  }
</style>